package com.xzc.kafka.action.consumer;

import org.apache.kafka.clients.consumer.ConsumerRecord;
import org.apache.kafka.clients.consumer.ConsumerRecords;
import org.apache.kafka.clients.consumer.KafkaConsumer;
import org.apache.kafka.common.PartitionInfo;
import org.apache.kafka.common.TopicPartition;
import org.apache.kafka.common.errors.WakeupException;

import java.util.ArrayList;
import java.util.List;
import java.util.Properties;

public class _5ControllYourself {

    public static void main(String[] args) {
        String topicName = "test-topic1";

        String groupID = "test-group";
        Properties props = new Properties();
        props.put("bootstrap.servers", "es1:19092,es2:19092,es3:19092");
        props.put("group.id", groupID);
//        props.put("enable.auto.commit", true);
        props.put("enable.auto.commit", false);
        props.put("auto.offset.reset", "earliest");
        props.put("key.deserializer", "org.apache.kafka.common.serialization.StringDeserializer");
        props.put("value.deserializer", "org.apache.kafka.common.serialization.StringDeserializer");

        KafkaConsumer<String, String> consumer = new KafkaConsumer<>(props);

        List<TopicPartition> partitions = new ArrayList<>();
        List<PartitionInfo> allPartitions = consumer.partitionsFor(topicName);
        if (allPartitions != null && !allPartitions.isEmpty()) {
            for (PartitionInfo partitionInfo : allPartitions) {
                partitions.add(new TopicPartition(partitionInfo.topic(), partitionInfo.partition()));
            }
            consumer.assign(partitions);
        }

        try {
            while (true) {
                ConsumerRecords<String, String> records = consumer.poll(Long.MAX_VALUE);
                for (ConsumerRecord<String, String> record : records) {
                    System.out.printf("topic=%s partition=%d offset=%d\n",
                            record.topic(),
                            record.partition(),
                            record.offset()
                    );
                }
                consumer.commitSync();
            }
        } catch (WakeupException e) {
        } finally {
            consumer.commitSync();
            consumer.close();
        }
    }

}
